package server.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;

import org.apache.log4j.Logger;

public class FileUtils {
	
	final static Logger logger = Logger.getLogger(FileUtils.class);
	
	public static Map<String, String> readMap(String fileName) {
		Map<String, String> map = new HashMap<String, String>();
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(
					new FileInputStream(fileName), "UTF-8"));
			String line = null;
			while ((line = reader.readLine()) != null) {
				line = line.trim();
				if (line.equals("") || line.startsWith("#")) {
					continue;
				}
				String[] temp = line.split("=", 2);
				if (temp.length == 2) {
					map.put(temp[0].trim(), temp[1].trim());
				}
			}
		} catch (Exception e) {
			logger.error("read {} fail ", e);
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (Exception e) {
			}
		}
		return map;
	}

	/**
	 * 读取文件内容
	 * 
	 * @param fileName
	 * @param encoding
	 * @return file content
	 */
	public static String readStringFile(String fileName, String encoding)
			throws Exception
	{
		StringBuffer sb = new StringBuffer();
		FileInputStream fis = new FileInputStream(fileName);
		BufferedReader reader = new BufferedReader(new InputStreamReader(fis,
				encoding));
		sb = new StringBuffer();
		while (reader.ready())
		{
			String line = reader.readLine();
			sb.append(line);
			sb.append("\r\n");
		}
		reader.close();
		fis.close();
		return sb.toString();
	}
	
	
	/**
	 * 以UTF-8读取文件内容
	 * @param fileName
	 * @param encoding
	 * @return
	 * @throws Exception
	 */
	public static String readStringFileUTF8(String fileName) throws Exception
	{
		return readStringFile(fileName, "UTF-8");
	}
	
	/**
	 * 读取一组txt文件，将文件解析成Map<[文件名], [文件内容]>
	 * 
	 * @param configPath
	 * @return
	 * @throws Exception
	 */
	public Map<String, String> loadTxtFiles(String configPath) throws Exception
	{
		List<String> files = listDirAllFiles(configPath);
		Map<String, String> map = new HashMap<String, String>();
		for (String fileName : files)
		{
			String txtStr = readStringFileUTF8(configPath
					+ File.separator + fileName + ".txt");
			map.put(fileName, txtStr);
		}
		return map;
	}
	
	public static List<String> listDirAllFiles(String root) {
		File dir = new File(root);
		root = dir.getAbsolutePath();

		List<String> fileNames = new ArrayList<String>();

		File[] files = dir.listFiles();
		for (File file : files) {
			listAllFiles(root, file, fileNames);
		}

		return fileNames;
	}


	private static void listAllFiles(String root, File dir,
			List<String> fileNames) {
		if (dir.isDirectory()) {
			java.io.File[] children = dir.listFiles();
			for (File file : children) {
				listAllFiles(root, file, fileNames);
			}
		} else {
			String path = dir.getAbsolutePath();
			String fileName = path.substring(root.length() + 1);
			fileNames.add(fileName);
		}
	}

	public static List<String> listJarAllEntries(String jarFileName)
			throws IOException {
		JarFile jarFile = new JarFile(jarFileName);
		List<String> entryNames = new ArrayList<String>();
		Enumeration<JarEntry> jarEntries = jarFile.entries();
		while (jarEntries.hasMoreElements()) {
			JarEntry jarEntry = jarEntries.nextElement();
			entryNames.add(jarEntry.getName());
		}

		return entryNames;

	}

	public static String getBaseName(String fileName) {
		String[] temp = fileName.split("[/\\\\]+");
		return temp[temp.length - 1];
	}

	public static String getPrefix(String fileName) {
		String baseName = getBaseName(fileName);
		String[] temp = baseName.split("\\.");
		return temp[0];
	}

	public static String getSuffix(String fileName) {
		String baseName = getBaseName(fileName);
		if (baseName.contains(".")) {
			if (baseName.startsWith(".")) {
				return baseName;
			} else {
				String[] temp = baseName.split("\\.");
				return temp[1];
			}
		} else {
			return "";
		}

	}

	
	
	/***
	 * 解压缩二进制文件
	 * @param data
	 * @return
	 */
	public static byte[] uncompress(byte[] data)
	{
		byte[] output = new byte[0];
		
		Inflater decompresser = new Inflater();
		
		decompresser.reset();
		
		decompresser.setInput(data);
		
		ByteArrayOutputStream o = new ByteArrayOutputStream(data.length);
		
		byte[] buf = new byte[1024];
		
		try
		{
			while(!decompresser.finished())
			{
				int i = decompresser.inflate(buf);
				o.write(buf, 0, i);
			}
			
			output = o.toByteArray();
		} 
		catch (DataFormatException e)
		{
			// TODO Auto-generated catch block
			output =  data;
			e.printStackTrace();
		}
		finally
		{
			try
			{
				o.close();
			} 
			catch (IOException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		decompresser.end();
		return output;
	}
	
}
